#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.security;

import ${package}.basic.module.menu.service.MenuService;
import ${package}.basic.module.role.service.RoleService;
import ${package}.basic.module.user.service.UserService;
import ${package}.common.bean.po.User;
import ${package}.common.bean.vo.SecurityUser;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * Description:
 *  UserDetailsService的实现类
 *  Spring Security 提供的登陆逻辑接口
 *
 * @author wupanhua
 * @date 2019/8/6 15:28
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Primary
@Component
@AllArgsConstructor
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    /**
     * 用户Mapper
     */
    private UserService userService;

    private RoleService roleService;

    private MenuService menuService;

    /**
     * Description:
     * <实现spring security 登录接口>
     * @author ywh
     * @date 11:09 2019/8/7
     * @param username 1
     * @return org.springframework.security.core.userdetails.UserDetails
     **/
    @Override
    public UserDetails loadUserByUsername(String username) {

        // 根据用户名查找用户信息
        User user = userService.findUserByUsername(username);

        if(user == null){
            throw new UsernameNotFoundException(String.format("'%s'.这个用户不存在", username));
        }

        // 返回一个UserDetail实现类
        SecurityUser securityUser = new SecurityUser();
        BeanUtils.copyProperties(user, securityUser);
        securityUser.setRoleArrayList(roleService.findRolesByUserKey(securityUser.getId()));
        if (!CollectionUtils.isEmpty(securityUser.getRoleArrayList())) {
            securityUser.setRoute(menuService.queryCurrentPermissionMenu(securityUser.getRoleArrayList()));
        }
        return securityUser;
    }

}
